package org.zjx.db;

import org.zjx.common.bean.Account;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccountDB {
    private static boolean isTableCreated = false;  // Flag to ensure the table is only created once
    private final SQLiteHelper dbHelper;

    public AccountDB() {
        dbHelper = SQLiteHelper.getSingleton();
        // Only create the table once when the instance is first created
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    // Create table for Account
    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS account (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    accountName TEXT NOT NULL,\n"
                + "    password TEXT NOT NULL,\n"
                + "    phone TEXT NOT NULL,\n"
                + "    general TEXT,\n"
                + "    trueName TEXT,\n"
                + "    trueCard TEXT,\n"
                + "    status INTEGER NOT NULL\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    // Insert an Account record
    public void insert(Account account) {
        String sql = "INSERT INTO account(accountName, password, phone, general, trueName, trueCard, status) VALUES(?, ?, ?, ?, ?, ?, ?)";
        Object[] params = {
                account.getAccountName(),
                account.getPassword(),
                account.getPhone(),
                account.getGeneral(),
                account.getTrueName(),
                account.getTrueCard(),
                account.getStatus()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Update an Account record
    public void update(Account account) {
        String sql = "UPDATE account SET accountName = ?, password = ?, phone = ?, general = ?, trueName = ?, trueCard = ?, status = ? WHERE id = ?";
        Object[] params = {
                account.getAccountName(),
                account.getPassword(),
                account.getPhone(),
                account.getGeneral(),
                account.getTrueName(),
                account.getTrueCard(),
                account.getStatus(),
                account.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Delete an Account record by ID
    public void deleteById(int id) {
        String sql = "DELETE FROM account WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    // Find Account by ID
    public Account findById(int id) {
        String sql = "SELECT * FROM account WHERE id = ?";
        Object[] params = {id};
        List<Account> accounts = dbHelper.executeQuery(sql, params, Account.class);
        if (accounts.isEmpty()) return null;
        return accounts.get(0);
    }

    // Find Account by Account Name
    public Account findByAccountName(String accountName) {
        String sql = "SELECT * FROM account WHERE accountName = ?";
        Object[] params = {accountName};
        List<Account> accounts = dbHelper.executeQuery(sql, params, Account.class);
        if (accounts.isEmpty()) return null;
        return accounts.get(0);
    }

    // Get all accounts
    public List<Account> findAll() {
        String sql = "SELECT * FROM account";
        Object[] params = {};
        return dbHelper.executeQuery(sql, params, Account.class);
    }

    // Paginated query for Accounts
    public Map<String, Object> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        String sql = "SELECT * FROM account LIMIT ? OFFSET ?";
        Object[] params = {pageSize, offset};
        List<Account> accounts = dbHelper.executeQuery(sql, params, Account.class);

        String countSql = "SELECT COUNT(*) FROM account";
        Object[] countParams = {};
        List<Integer> totalRecordsList = dbHelper.executeQuery(countSql, countParams, Integer.class);
        int totalRecords = totalRecordsList.isEmpty() ? 0 : totalRecordsList.get(0);

        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("accountList", accounts);
        result.put("totalRecords", totalRecords);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);

        return result;
    }

    // Clear all Account data
    public void clearData() {
        dbHelper.clearData("account");
    }

    // Drop the Account table
    public void dropTable() {
        dbHelper.dropTable("account");
    }
}
